package org.geotools.toolbox;

import java.awt.Dimension;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.geotools.coverage.grid.GridCoverage2D;
import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.feature.NameImpl;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.process.Process;
import org.geotools.process.Processors;
import org.geotools.process.feature.AbstractFeatureCollectionProcessFactory;
import org.geotools.utils.FileUtils;
import org.opengis.util.ProgressListener;

public class Shp2Raster {
	public static void execute(String inpath, String field_name,
			Double cellsize_meter, String outpath) throws Exception {
		// to force geotools into using lon/lat order for geographic data
		System.setProperty("org.geotools.referencing.forceXY", "true");
		System.out.println("Beginning Shp2Raster Toolbox execution....");
		// /////////////////////////////////////////////////////////////////////
		FileDataStore store = FileDataStoreFinder
				.getDataStore(new File(inpath));
		SimpleFeatureSource featureSource = store.getFeatureSource();
		SimpleFeatureCollection features = featureSource.getFeatures();

		ReferencedEnvelope bounds = features.getBounds();
		if (cellsize_meter == null) {
			cellsize_meter = (double) 200;
		}
		Dimension gridDim = new Dimension(
				(int) (bounds.getWidth() / cellsize_meter),
				(int) (bounds.getHeight() / cellsize_meter));
		ProgressListener monitor = null;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(AbstractFeatureCollectionProcessFactory.FEATURES.key, features);
		map.put("attribute", field_name);
		map.put("rasterWidth", gridDim.width);
		map.put("rasterHeight", gridDim.height);
		map.put("bounds", bounds);
		Process p = Processors.createProcess(new NameImpl("vec",
				"VectorToRaster"));
		Map<String, Object> result = p.execute(map, monitor);
		GridCoverage2D cov = (GridCoverage2D) result.get("result");
		if(outpath!=null){
        	System.out.print("writing result..."); 
        	FileUtils.exportRasterfile(cov, outpath);
             System.out.println("done writing result!");
        }
	}
}
